package com.cn.shuangzi.ad.retrofit;


import com.cn.shuangzi.SZManager;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.ADUtil;

import org.apaches.commons.codec.digest.DigestUtils;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by CN on 2018-3-13.
 */

public class ADRequestInterceptor implements Interceptor{
    public static final String APP_ID = "0yfoZsFJJk7PeFwZ";
    private static final String APP_KEY = "AiPCKjWxSYCVJw9WS3kOqVuC8gZ7LFBq";
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        HttpUrl originalHttpUrl = original.url();
        long time = System.currentTimeMillis() / 1000;
        HttpUrl.Builder builderHttp = originalHttpUrl.newBuilder()
                .addQueryParameter("appTime",String.valueOf(time))
                .addQueryParameter("appId", APP_ID)
                .addQueryParameter("appSign",makeSign(APP_ID,APP_KEY,time));
        HttpUrl url = builderHttp.build();
        Request.Builder requestBuilder = original.newBuilder()
                .url(url);

        Request request = requestBuilder.build();
        if("POST".equals(request.method())){
            StringBuilder sb = new StringBuilder();
            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                for (int i = 0; i < body.size(); i++) {
                    sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
                }
                sb.delete(sb.length() - 1, sb.length());
            }
            ADUtil.logError("postParams:"+sb);
        }else{
            ADUtil.logError("getParams:"+originalHttpUrl.query());
        }
        SZManager.getInstance().onUMEvent(ADConst.AD_SERVICE_API_REQUEST_EVENT_ID);
        return chain.proceed(request);
    }
    private String makeSign(String appId, String appKey, long currentTime){
        String sha1 = DigestUtils.sha1Hex(currentTime + appKey + currentTime);
        String md5  = DigestUtils.md5Hex(sha1 + appId);
        return md5;
    }
}
